import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '@/utils/auth'
import { handleRouteComponent } from '@/utils/index'
import { getStudentRoute, getTeacherRoute } from '@/api/user'

// 标记是否已添加动态路由
let hasAddedRoutes = false

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login.vue'),
    },
    {
      // 刷题页面
      path: '/practice',
      name: 'Practice',
      component: () =>
        import('@/views/student/views/practice/exampractice.vue'),
    },
    {
      // 开始考试
      path: '/startExam',
      name: 'startExam',
      component: () => import('@/views/student/views/exam/examTest.vue'),
    },
    // 404 路由配置
    {
      path: '/404',
      name: 'NotFound',
      component: () => import('@/views/404.vue'),
    },
  ],
})

// 路由规则
router.beforeEach(async (to, from, next) => {
  try {
    // 获取store
    const { useUserStore } = await import('@/store/modules/user')
    const { useRouteStore } = await import('@/store/modules/route')
    const userStore = useUserStore()
    const routeStore = useRouteStore()

    // 检查是否已登录
    const token = userStore.token || getToken()
    const isLoggedIn = !!token
    const role = localStorage.getItem('role')

    // 如果访问登录页
    if (to.path === '/login') {
      if (isLoggedIn) {
        next({ path: role === 'teacher' ? '/teacher/home' : '/student/exam' })
      } else {
        next()
      }
      return
    }

    // 如果访问其他页面且未登录
    if (!isLoggedIn) {
      next({ path: '/login' })
      return
    }

    // 动态添加路由（确保页面刷新后也能正确加载路由）
    if (!hasAddedRoutes) {
      console.log('开始添加动态路由，用户角色:', role)
      try {
        // 根据角色获取路由
        let route = null
        if (role === 'teacher') {
          // 从Pinia获取路由数据
          await routeStore.loadTeacherRoutes()
          route = routeStore.teacherRoutes
        } else {
          // 从Pinia获取路由数据
          await routeStore.loadStudentRoutes()
          route = routeStore.studentRoutes
        }

        if (route) {
          // 处理路由组件
          const processedRoute = handleRouteComponent(route)

          // 添加动态路由
          router.addRoute(processedRoute)

          // 添加404兜底
          router.addRoute({
            path: '/:pathMatch(.*)*',
            redirect: '/404',
          })

          hasAddedRoutes = true
          // 标记路由状态已加载
          routeStore.setLoaded(true)
          console.log('动态路由添加成功')

          // 如果是访问根路径，重定向到相应首页
          if (to.path === '/') {
            next({
              path: role === 'teacher' ? '/teacher/home' : '/student/exam',
              replace: true,
            })
            return
          }

          // 重新导航到目标页面以确保路由匹配正确
          next({ ...to, replace: true })
          return
        }
      } catch (error) {
        console.error('动态添加路由失败:', error)
      }
    }

    // 如果没有角色信息，尝试获取用户信息
    if (!role) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        userStore.resetState()
        routeStore.clearRoutes() // 清除路由缓存
        next({ path: '/login' })
        return
      }
    }

    // 路由权限检查
    if (to.path.startsWith('/teacher') && role !== 'teacher') {
      next({ path: '/404' })
      return
    }

    if (to.path.startsWith('/student') && role !== 'student') {
      next({ path: '/404' })
      return
    }

    // 继续导航
    next()
  } catch (error) {
    console.error('路由守卫出错:', error)
    next('/login')
  }
})

export default router
